var eventViewWindow;
var editorField;
var gridTable;

var initCalendar = {
	createDatePickers : function() {
		// Convert date fields to Ext DateField		
		var dateStart = new Ext.form.DateField({
			width: 100,
			allowBlank: true,
			format: 'm/d/Y',
			applyTo: 'eDateStart'
		});
		var dateEnd = new Ext.form.DateField({
			width: 100,
			allowBlank: true,
			format: 'm/d/Y',
			applyTo: 'eDateEnd'
		});
	},
	createEventViewWindow : function() {
		/*
		 * Create event view window
		 */
		if(!eventViewWindow){
            eventViewWindow = new Ext.Window({
				el:          'eventViewWindow',
                id:          'eventViewWindow',
                width:       550,
                height:      350,
                resizable:   true,
                closeAction: 'hide',
                plain:       true,
                title:       '<b>Event Viewer</b>',
                shadow:      false,
				autoScroll:  true,
				tbar:[{
                        tooltip:'Edit this event',
                        iconCls:'toolbarEdit',
						handler : function(){
			                var eID = $F('eID');
							calendarUpdateObj.getEventData(eID,'edit');
			            }
                    }, '-', {
                        tooltip:'Delete this event',
                        iconCls:'toolbarDelete',
						handler : function(){
			                var eID = $F('eID');
							//confirmDelete(eID,'event');
			                trashUpdateObj.sendToTrash(eID,'event');
			            }
                    }]
            });            
        }		
        eventViewWindow.show();
        return eventViewWindow;	
	}
}

var calendarNavigateObject = {
	newMonth : function(month,year,size) {
		var params = 'handler=displayCalendar&month='+month+'&year='+year+'&size='+size;
		
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,	
			onSuccess: function(transport) {
				calendarNavigateObject.displayCalendar(transport.responseText);			
			},
			onFailure: function() {
				alert('Oops!');
			}		
		});
	},
	displayCalendar : function(calString) {
		$('calContainer').innerHTML = calString;
		$('calContainer').style.display   = 'block';	
	},
	newMonthBig : function(month,year) {
		if ( (month == '0') && (year == '0') ) {
			month = $('thisMonth').value;
			year  = $('thisYear').value;
		} else {
			$('thisMonth').value = month;
			$('thisYear').value = year;	
		}
		
		// Set month and year select
		var monthOptions = $('monthSelect').options;
		var yearOptions  = $('yearSelect').options;
		
		for(var a=0;a<=((monthOptions.length)-1);a++) {
			if (monthOptions[a].value == month) {
				$('monthSelect').options[a].selected = true;
			}
		}
		for(a=0;a<=((yearOptions.length)-1);a++) {
			if (yearOptions[a].value == year) {
				$('yearSelect').options[a].selected = true;
			}
		}
		var params = 'handler=displayCalendarFull&month='+month+'&year='+year;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				calendarNavigateObject.displayCalendarFull(transport.responseText);
			}
		});
	},
	monthPrevNext : function(dir) {
		var currentMonth = $('thisMonth').value;
		var currentYear  = $('thisYear').value;
		if (dir == 'prev') {
			// What's the previous month
			if (currentMonth == '1') {
				var newMonth = 12;
				var newYear  = currentYear-1;
			} else {
				var newMonth = currentMonth-1;
				var newYear  = currentYear;
			}
		} else {
			if (currentMonth == '12') {
				var newMonth = 1;
				var newYear  = parseInt(currentYear)+parseInt(1);
			} else {
				var newMonth = parseInt(currentMonth)+parseInt(1);
				var newYear  = currentYear;
			}
		}
		this.newMonthBig(newMonth,newYear);
	},
	newMonthRelay : function() {
		var mo = $('monthSelect');
		mo     = mo[mo.selectedIndex].value;
		var yr = $('yearSelect');
		yr     = yr[yr.selectedIndex].value;
		this.newMonthBig(mo,yr);
	},
	displayCalendarFull : function(calString) {
		var calArray  = calString.split('~~|~~');
		var calString = calArray[0];
		var month     = calArray[1];
		var year      = calArray[2];
		
		$('dateTitleDisplay').innerHTML = '<span class="ltGrayText">Currently viewing</span> '+month+' '+year;
		$('calContainerFull').innerHTML = calString;
	}
}

var calendarSupportObj = {
	calDayNumHover : function(listDay,origBgClass) {
		$('calDayNum'+listDay).className = 'calDayHover';
	},
	calDayNumUnHover : function(listDay,origBgClass) {
		$('calDayNum'+listDay).className = origBgClass;
	},
	openEventForm : function(date,action) {
		$('buttonNew').style.display = 'none';
		new Effect.SlideDown('formNewEvent', {direction: 'top', duration: .2});
		
		/*
		 * Populate start date field
		 */
		var extDate = mysqlToExtDate(date);
		$('eDateStart').value = extDate;
		if (action == 'add') {
			$('formTitle').innerHTML = '<h1>Add new event for '+extDate+'</h1>'; 	
		} else if (action == 'edit') {
			$('formTitle').innerHTML = '<h1>Edit event for '+extDate+'</h1>';
		}		
		
		$('completeDate').value = date;
		$('formAction').value   = action;
	},
	closeEventForm : function() {
		new Effect.SlideUp('formNewEvent', {direction: 'top', duration: .2});
		$('buttonNew').style.display = '';
		$('formTitle').innerHTML = '';
		$('formAction').value = 'add';
		
		/*
		 * Clear form
		 */
		this.clearEventForm();		
	},
	clearEventForm : function() {
		$('formAction').value = 'add';
		$('eType').options[0].selected = true;
		$('eName').value = '';
		$('ePublic').checked = true;
		tinyMCE.getInstanceById('eDesc').getBody().innerHTML = '';	
		$('eDateStart').value = '';
		$('eDateEnd').value   = '';
		$('calHourSelectStart').options[0].selected = true;
		$('calMinSelectStart').options[0].selected = true;
		$('calAmPmSelectStart').options[0].selected = true;
		$('calHourSelectEnd').options[0].selected = true;
		$('calMinSelectEnd').options[0].selected = true;
		$('calAmPmSelectEnd').options[0].selected = true;
		$('eReg').checked = false;
		$('eSpeakers').value = '';
		$('eURL').value = 'http://';
		$('eRegURL').value = 'http://';
		$('eLocation').value = '';
		$('eAddress').value = '';
		$('eCity').value = '';
		$('eState').options[0].selected = true;
		$('eContactPerson').value = '';
		$('eContactPhone').value = '';
		$('eContactEmail').value = '';
		$('eVenueSize').value = '';
		/*
		 * Conceal advanced form panel
		 */
		$('formAdvancedPanel').style.display = 'none';
		$('showAdvancedLink').style.display  = '';
	},
	showAdvancedForm : function() {
		new Effect.SlideDown('formAdvancedPanel', {direction: 'top', duration: .2});
		$('showAdvancedLink').style.display = 'none';
	},
	renderEventView : function(jsonString) {
		var jsonObject = eval('('+jsonString+')');
		
		var eID        = jsonObject.EventID;
		var eTitle     = jsonObject.EventName;
		var eDesc      = jsonObject.EventDescription;
		var eDateStart = jsonObject.StartDate;
		var eDateEnd   = jsonObject.EndDate;
		var eLocation  = jsonObject.LocationString;
		var eContact   = jsonObject.ContactString;
		var eContactURL    = jsonObject.ContactURL;
		var eRegURL        = jsonObject.RegistrationLink;
		var eVenue         = jsonObject.VenueSize;
		var ePublic        = jsonObject.Public;		
		var GoogleLocation = jsonObject.GoogleLocation;		
					
		initCalendar.createEventViewWindow();
		var windowHTML = '<div style="padding: 5px; background: #fff;"><p>';
		windowHTML    += '<h2>'+eTitle+'</h2>';		
		windowHTML    += eDateStart;
		if (eDateEnd != '') {
			windowHTML += ' to '+eDateEnd;
		}
		windowHTML    += '<br /><br />';
		if (eDesc != '') {
			windowHTML += eDesc+'<br />';
		}
		windowHTML += '<div style="float: left; width: 50%; vertical-align: top;">';
		if (eContactURL != '') {
			windowHTML += '<a href="'+eContactURL+'" target="_blank">'+eContactURL+'</a><br />';
		}
		if (eContact != '') {
			windowHTML += '<br /><b>Contact:</b><br />'+eContact+'<br />';
		}
		windowHTML += '</div><div style="float: left; width: 50%; vertical-align: top;">';
		if (eLocation != '') {
			windowHTML += '<br /><b>Location:</b><br />'+eLocation+'<br />';
		}
		windowHTML += '</div><div style="clear: left;"></div>';
		if (GoogleLocation != 0) {				
			windowHTML += '<div id="mapDiv" style="width: 500x; height: 300px;"></div>';
		}
		
		windowHTML    += '</p></div>';
		eventViewWindow.body.update(windowHTML);
		
		if (!$('calendarPage')) {
			/*
			 * If we're not on the calendar page, 
			 * turn off the event view window toolbar.
			 */
			Ext.getCmp('eventViewWindow').getTopToolbar().hide();			
		}
		
		/*
		 * Render Goole Map???
		 */
		if (GoogleLocation != 0) {	
			var pointerText = '<b>'+eTitle+'</b><br />'+eLocation;
			showGoogleMap(GoogleLocation,'mapDiv',pointerText);	
		}	
	}
}

var calendarUpdateObj = {
	saveEvent : function() {
		var eDesc = tinyMCE.get('eDesc').getContent();
		
        var dataString = {
			eID:            $F('eID'),
			action:         $F('formAction'),
			completeDate:   $F('completeDate'),
			mo:             $F('thisMonth'),
			yr:             $F('thisYear'),
			eType:          $F('eType'),
			eName:          $F('eName'),
			eDesc:          eDesc,
			eURL:           $F('eURL'),
			eRegURL:        $F('eRegURL'),
			eDateStart:     $F('eDateStart'),
			eDateEnd:       $F('eDateEnd'),
			eHourStart:     $F('calHourSelectStart'),
			eMinStart:      $F('calMinSelectStart'),
			eAPStart:       $F('calAmPmSelectStart'),
			eHourEnd:       $F('calHourSelectEnd'),
			eMinEnd:        $F('calMinSelectEnd'),
			eAPEnd:         $F('calAmPmSelectEnd'),
			eLocation:      $F('eLocation'),
			eAddress:       $F('eAddress'),
			eState:         $F('eState'),
			eCity:          $F('eCity'),
			eZip:           $F('eZip'),
			eContactPerson: $F('eContactPerson'),
			eContactPhone:  $F('eContactPhone'),
			eContactEmail:  $F('eContactEmail'),
			eSpeakers:      $F('eSpeakers'),
			eVenueSize:     $F('eVenueSize'),
			ePublic:        $F('ePublic'),
			eReg:           $F('eReg')
		};	
		jsonString = Object.toJSON(dataString);
		var reqHash = {
						'handler'    : 'saveEvent', 
						'jsonString' : jsonString
						};	
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: reqHash,
			onSuccess: function(transport) {
				/*
				 * Close entry form
				 */
				calendarSupportObj.closeEventForm();
				calendarNavigateObject.displayCalendarFull(transport.responseText);
			},
			onFailure: function() {
				alert('Oops!');
			}	
		});
	},
	getEventData : function(eventID,action) {
		$('eID').value = eventID;
		var params = 'handler=getEvent&eventID='+eventID+'&action='+action;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				if (action == 'view') {
					calendarSupportObj.renderEventView(transport.responseText);
				} else if (action == 'edit') {
					calendarUpdateObj.renderEditForm(transport.responseText);
					/*
					 * Close event window
					 */
					if (eventViewWindow) {
						eventViewWindow.hide();
					}
				}				
			},
			onFailure: function() {
				alert('Oops!');
			}	
		});
	},
	renderEditForm : function (jsonString) {
		var jsonObject = eval('('+jsonString+')');
		
		var eID        = jsonObject.EventID;
		var eType      = jsonObject.EventCat;
		var eTitle     = jsonObject.EventName;
		var eDesc      = jsonObject.EventDescription;
		var eDateStart = jsonObject.StartDate;
		var eDateEnd   = jsonObject.EndDate;
		var eHourStart = jsonObject.StartHour;
		var eHourEnd   = jsonObject.EndHour;
		var eMinStart  = jsonObject.StartMin;
		var eMinEnd    = jsonObject.EndMin;	
		var eAmPmStart = jsonObject.StartAmPm;
		var eAmPmEnd   = jsonObject.EndAmPm;	
		var eLocation  = jsonObject.Location;
		var eAddress   = jsonObject.LocationAddress;
		var eCity      = jsonObject.LocationCity;
		var eState     = jsonObject.LocationState;
		var eZip       = jsonObject.LocationZip;		
		var eContact   = jsonObject.ContactPerson;
		var eContactPhone = jsonObject.ContactPhone;
		var eContactEmail = jsonObject.ContactEmail		
		var eContactURL    = jsonObject.ContactURL;
		var eReg           = jsonObject.RegistrationRequired;
		var eRegURL        = jsonObject.RegistrationLink;
		var eVenue         = jsonObject.VenueSize;
		var ePublic        = jsonObject.Public;		
		var eSpeakers      = jsonObject.Speakers;		
		
		/*
		 * Populate form
		 */
		$('formAction').value = 'edit';
		$('eID').value        = eID;
		
		/*
		 * Category select
		 */
		var optionsCat = $('eType').options;
		for(a=0;a<optionsCat.length;a++) {
			if ($('eType').options[a].value == eType) {
				$('eType').options[a].selected = true;
			}
		}
		/*
		 * State select
		 */
		var optionsState = $('eState').options;
		for(a=0;a<optionsState.length;a++) {
			if ($('eState').options[a].value == eState) {
				$('eState').options[a].selected = true;
			}
		}
		
		if (ePublic != 1) {
			$('ePublic').checked = false;
		}
		
		$('eName').value = eTitle;
		tinyMCE.getInstanceById('eDesc').getBody().innerHTML = eDesc;	
		$('eDateStart').value = eDateStart;
		$('eDateEnd').value   = eDateEnd;
		
		/*
		 * Hour, Min, AmPm Selects
		 */
		var optionsHourStart = $('calHourSelectStart').options;
                if (eHourStart>12) {
                    eHourStart = parseInt(eHourStart-12);
                }
		for(a=0;a<optionsHourStart.length;a++) {
			if ($('calHourSelectStart').options[a].value == eHourStart) {
				$('calHourSelectStart').options[a].selected = true;
			}
		}
		var optionsMinStart = $('calMinSelectStart').options;
		for(a=0;a<optionsMinStart.length;a++) {
			if ($('calMinSelectStart').options[a].value == eMinStart) {
				$('calMinSelectStart').options[a].selected = true;
			}
		}
		var optionsAmPmStart = $('calAmPmSelectStart').options;
		for(a=0;a<optionsAmPmStart.length;a++) {
			if ($('calAmPmSelectStart').options[a].value == eAmPmStart) {
				$('calAmPmSelectStart').options[a].selected = true;
			}
		}                
		var optionsHourEnd = $('calHourSelectEnd').options;
                if (eHourEnd>12) {
                    eHourEnd = parseInt(eHourEnd-12);
                }
		for(a=0;a<optionsHourEnd.length;a++) {
			if ($('calHourSelectEnd').options[a].value == eHourEnd) {
				$('calHourSelectEnd').options[a].selected = true;
			}
		}
		var optionsMinEnd = $('calMinSelectEnd').options;
		for(a=0;a<optionsMinEnd.length;a++) {
			if ($('calMinSelectEnd').options[a].value == eMinEnd) {
				$('calMinSelectEnd').options[a].selected = true;
			}
		}
		var optionsAmPmEnd = $('calAmPmSelectEnd').options;
		for(a=0;a<optionsAmPmEnd.length;a++) {
			if ($('calAmPmSelectEnd').options[a].value == eAmPmEnd) {
				$('calAmPmSelectEnd').options[a].selected = true;
			}
		}
		
		$('eSpeakers').value = eSpeakers;
		$('eURL').value      = eContactURL;
		$('eRegURL').value   = eRegURL;
		$('eLocation').value = eLocation;
		$('eAddress').value  = eAddress;
		$('eCity').value     = eCity;
		$('eZip').value      = eZip;
		$('eContactPerson').value = eContact;
		$('eContactPhone').value  = eContactPhone;
		$('eContactEmail').value  = eContactEmail;
		$('eVenueSize').value     = eVenue;
		
		/*
		 * Close event viewer
		 */
		if (eventViewWindow) {
			eventViewWindow.hide();
		}
		
		/*
		 * Render form
		 */
		calendarSupportObj.openEventForm();
	},
	deleteEvent : function(eventID) {
		var params = 'handler=deleteEvent&eventID='+eventID;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				calendarUpdateObj.returnDeleteEvent(transport.responseText);				
			}
		});
	},
	returnDeleteEvent : function(eventID) {
		Effect.Fade('eventContainer'+eventID, {delay: .1, duration: 1});
		/*
		 * Close event window
		 */
		if (eventViewWindow) {
			eventViewWindow.hide();
		}
	}
}

var getEventsObj = {
	getEventsForContactForm : function(gridType){
		// Current date
		var today = dateToMySQL('today');
		var params = 'handler=getEvents&mo=&yr=&size=&startDate='+today+'&endDate=&scope=public&renderType=json';
			
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport){
				gridTable = getEventsObj.renderEventsForContactForm(transport.responseText, gridType);
			}
		});
	},
	renderEventsForContactForm : function(jsonString,gridType) {
          var jsonObject = eval('('+jsonString+')');
		var totalEvents = (jsonObject.Events.length)-1;
		
		var gridHTML = '<div><table class="dataTable" style="width: 100%;">';
		if (gridType == 'referral') {
			gridHTML    += '<tr><th>Refer</th><th>Title</th><th style="width: 100px;">Date</th></tr>';			

               var selectString = '';
			for (i = 0; i <= totalEvents; i++) {
				var eventID    = jsonObject.Events[i].EventID;
				var eventTitle = jsonObject.Events[i].EventName;
				var startDate  = jsonObject.Events[i].StartDateFormat;
				var endDate    = jsonObject.Events[i].EndDateFormat;
				
				gridHTML += '<tr id="eventContainer'+eventID+'">';
				gridHTML += '<td style="text-align: center;"><input type="checkbox" id="referralEventID_'+eventID+'" class="referralEvents" value="'+eventID+'" /></td>';
				gridHTML += '<td><a href="#" onClick="calendarUpdateObj.getEventData('+eventID+',\'view\'); return false;">'+eventTitle+'</a></td>';
				gridHTML += '<td>'+startDate+'</td></tr>';

                    var option = document.createElement('option');
                    option.setAttribute('value',eventID);
                    option.appendChild(document.createTextNode(eventTitle+' on '+startDate));
                    $('eventSelectClientInfo').appendChild(option);

                    //selectString += '<option value="'+eventID+'">'+eventTitle+' on '+startDate+'</option>';
			}
			gridHTML += '</table></div>';		
			$('referralEventGrid').innerHTML = gridHTML;
               //$('eventSelectClientInfo').innerHTML = selectString;

		} else {
			
		}		
	}
}